<template>
  <div class="login-container">
    <div class="panel-left"></div>
    <div class="panel-right">
      <h2>欢迎回来!</h2>
      <p>登录以继续</p>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="密码" show-password />
        </el-form-item>
        <el-form-item class="form-actions">
          <el-button class="sign-btn" type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
        <div class="forgot-password">
          <a href="#">忘记密码?</a>
        </div>
        <div class="register-link">
          <span>没有账户? </span><a href="#" @click.prevent="goToRegister">注册</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/user'
import type { LoginResult } from '@/api/user'
import type { ApiResponse } from '@/types/api'
import { useUserStore } from '@/stores/user'
import { resetRouter, addRoutes } from '@/router'

const router = useRouter()
const formRef = ref()
const userStore = useUserStore()

const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const axiosResponse = await login({
      username: form.username,
      password: form.password
    })

    const response = axiosResponse as unknown as ApiResponse<LoginResult>

    if (response.code !== 200 || !response.data) {
      ElMessage.error(response.msg || '登录失败')
      return
    }

    const loginData = response.data
    sessionStorage.setItem('token', loginData.token)
    sessionStorage.setItem('userId', loginData.userId)
    sessionStorage.setItem('username', loginData.username)

    userStore.setToken(loginData.token)
    userStore.setUserInfo(loginData)

    ElMessage.success('登录成功')

    // 顺序：重置旧路由 → 添加新路由 → 跳转
    try {
      resetRouter()
      addRoutes(userStore.permissions)
      router.replace('/home')
    } catch (error: any) {
      ElMessage.error(error?.message || '路由配置失败')
      userStore.logout()
      router.replace('/login')
    }
  } catch (error: any) {
    console.error('登录异常:', error)
    ElMessage.error(error?.message || '网络错误，请稍后重试')
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Quicksand&display=swap');

.login-container {
  display: flex;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.panel-left {
  flex: 0 0 60%;
  background-image: url('/Login.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.panel-right {
  flex: 0 0 40%;
  background-color: white;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.panel-right h2 {
  font-family: 'Quicksand', sans-serif;
  font-size: 2.2rem;
  font-weight: 700;
  margin-bottom: 10px;
  color: #333;
}

.panel-right p {
  color: #777;
  font-size: 1.1rem;
  margin-bottom: 30px;
}

.login-form {
  width: 100%;
  max-width: 300px;
}

.login-form :deep(.el-input__wrapper) {
  background: #f5f5f5;
  border-radius: 8px;
  box-shadow: none;
  margin-bottom: 15px;
}

.login-form :deep(.el-input__inner) {
  font-size: 1rem;
  padding: 12px 15px;
}

.form-actions {
  margin-bottom: 10px;
}

.sign-btn {
  width: 100%;
  background: #466fff;
  color: #fff;
  font-weight: 700;
  border-radius: 8px;
  padding: 14px 0;
  font-size: 1.1rem;
  box-shadow: 0 4px 10px rgba(70, 111, 255, 0.2);
  transition: all 0.2s;
  border: none;
}

.sign-btn:hover {
  background: #3355cc;
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(70, 111, 255, 0.25);
}

.forgot-password, .register-link {
  width: 100%;
  max-width: 300px;
  text-align: right;
  margin-top: 5px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
}

.forgot-password a, .register-link a {
  color: #466fff;
  text-decoration: none;
  font-size: 0.9rem;
}

.forgot-password a:hover, .register-link a:hover {
  text-decoration: underline;
}
</style>
